package com.example.baseweb.service.impl;

import com.example.baseweb.common.PageResponse;
import com.example.baseweb.entity.User;
import com.example.baseweb.repository.UserRepository;
import com.example.baseweb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Override
    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
    
    @Override
    public User getUserByOpenid(String openid) {
        return userRepository.findByOpenid(openid);
    }
    
    @Override
    public User updateUserStatus(Long id, Integer status) {
        User user = getUserById(id);
        if (user != null) {
            user.setStatus(status);
            user.setUpdateTime(LocalDateTime.now());
            return userRepository.save(user);
        }
        return null;
    }
    
    @Override
    public List<User> getUsersByStatus(Integer status) {
        return userRepository.findByStatus(status);
    }
    
    @Override
    public PageResponse<User> getUserPage(int page, int size, String nickname, String phone) {
        Pageable pageable = PageRequest.of(page - 1, size);
        
        Specification<User> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            if (StringUtils.hasText(nickname)) {
                predicates.add(criteriaBuilder.like(root.get("nickname"), "%" + nickname + "%"));
            }
            
            if (StringUtils.hasText(phone)) {
                predicates.add(criteriaBuilder.like(root.get("phone"), "%" + phone + "%"));
            }
            
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        
        Page<User> userPage = userRepository.findAll(spec, pageable);
        return PageResponse.of(userPage.getContent(), userPage.getTotalElements(), size, page);
    }
} 